<!--用户脚本编辑窗口-->
<template>
  <div class="logic-user-script-dialog us-none">
    <div class="user-script-params">
      <div class="user-script-param">
        <div>
          <label>
            输入变量
          </label>
          <!--                添加输出变量-->
          <!--          <i-->
          <!--              class="el-icon-circle-plus-outline m-top-10 m-bottom-10 cursor-pointer"-->
          <!--              icon="el-icon-plus"-->
          <!--              type="success"-->
          <!--              size="mini"-->
          <!--              @click.prevent="addScriptInputParam()"-->
          <!--              circle-->
          <!--          ></i>-->
          <el-icon @click.prevent="addScriptInputParam()"
                   class="el-icon-circle-plus-outline m-top-10 m-bottom-10 cursor-pointer">
            <CirclePlus/>
          </el-icon>
        </div>
        <div class="user-script-param-list">
          <div
              class="user-script-param-item"
              v-for="(item,index) in LogicUserScript.NodeLogic.Script.InputParams"
              :key="index"
          >
            <el-input
                placeholder="输入变量名称"
                clearable
                v-model="item.TargetParamName"
                size="small"
                style="margin-right: 10px;width: 160px"
            >
            </el-input>
            <el-select
                clearable
                v-model="item.ValueType"
                placeholder="请选择类型"
                size="small"
                style="width: 110px; margin-right: 10px;"
            >
              <el-option
                  v-for="item in ValueTypes"
                  :key="item"
                  :label="item"
                  :value="item"
              >
              </el-option>
            </el-select>
            <data-source-input
                :datasource-item="item"
                :node-id="item.DataSourceId"
                :param-name="item.ParamName"
                null-message="请选择数据来源（不能为空）"
                @change="onChange($event,index)"
            />
            <el-button
                icon="Delete"
                style="color: red"
                @click.prevent="deleteScriptInputParam(index)"
                type="text"
                size="small"
                circle
            ></el-button>
          </div>
        </div>
      </div>
      <div class="user-script-param">
        <div>
          <label>
            输出变量
          </label>
          <!--                添加输出变量-->
          <!--          <i-->
          <!--              class="el-icon-circle-plus-outline m-top-10 m-bottom-10 cursor-pointer"-->
          <!--              icon="el-icon-plus"-->
          <!--              type="success"-->
          <!--              size="mini"-->
          <!--              @click.prevent="addScriptOutParam()"-->
          <!--              circle-->
          <!--          ></i>-->
          <el-icon @click.prevent="addScriptOutParam()"
                   class="el-icon-circle-plus-outline m-top-10 m-bottom-10 cursor-pointer">
            <CirclePlus/>
          </el-icon>
        </div>
        <div class="user-script-param-list">
          <div
              class="user-script-param-item"
              v-for="(item,index) in LogicUserScript.NodeLogic.Script.OutParams"
              :key="index"
          >
            <el-input
                placeholder="输出变量名称"
                clearable
                v-model="item.ParamName"
                size="small"
                style="margin-right: 10px;width: 160px"
            >
            </el-input>
            <el-select
                clearable
                v-model="item.ValueType"
                placeholder="请选择类型"
                size="small"
                style="width: 110px; margin-right: 10px;"
            >
              <el-option
                  v-for="item in ValueTypes"
                  :key="item"
                  :label="item"
                  :value="item"
              >
              </el-option>
            </el-select>
            <el-button
                icon="Delete"
                style="color: red"
                @click.prevent="deleteScriptOutParam(index)"
                type="text"
                size="small"
                circle
            ></el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="user-script-space">
      <!--     脚本编辑区域 -->
      <div class="user-script-edit">
        <monaco-editor
            v-model:modelValue="LogicUserScript.NodeLogic.Script.ScriptCode"
            height="641px"
            language="csharp"/>
        <!--        <script-edit v-model="LogicUserScript.NodeLogic.Script.ScriptCode"></script-edit>-->
        <!--        <el-input-->
        <!--            v-model="LogicUserScript.NodeLogic.Script.ScriptCode"-->
        <!--            type="textarea"-->
        <!--            autosize-->
        <!--            :rows="33"-->
        <!--            placeholder="请编辑脚本"-->
        <!--        >-->
        <!--        </el-input>-->
      </div>
      <div class="user-script-build"></div>
    </div>
    <div class="user-script-desc" v-if="CompileMessage">
      <div class="user-script-input">
      </div>
      <div>
        <span>文档说明</span>
      </div>
      <div style="white-space: pre-line" v-html="CompileMessage"></div>
    </div>
  </div>
</template>

<script>
import Utils from '../../../../utils/Common'
import FlowNodeDataApi from '@/api/flow/FlowNodeDataApi'
import { AppParams } from '@/utils/appParams'
import EventBus from '../../../../libs/EventBus'
import NodeConfigMixin from '../../../../libs/NodeConfigMixin'
// import ScriptEdit from './ScriptEdit.vue'
import { MonacoEditor } from "@/components/Pages/MonacoEditor/index";
import { MessageError, MessageWarning } from "@/utils";
// const lodash = require('../../../../../../../public/libs/lodash.min-4.17.21.js')
// import lodash from '../../../../../../../public/libs/lodash.min-4.17.21.js'
import DataSourceInput from '../../components/NodeInputSourceDataComponent.vue'
import { Emitter } from "@/utils/Emitter";

export default {
  mixins: [NodeConfigMixin],
  name: 'UserScriptDialog',
  components: { MonacoEditor, DataSourceInput },
  data () {
    return {
      notifyC: null,
      // SourceNode: null,
      established: ['OK', 'NG'],
      triggerNodes: [{ name: null, id: null }],
      optionDrivers: [],
      ValueTypes: AppParams.COMMON.DATA_TYPE,
      // nodeInputParams: [],
      LogicUserScript: {
        NodeLogic: {
          Script: {
            InputParams: [{
              TargetParamName: 'Input0',
              ParamName: null,
              ValueType: 'int',
              DataSource: null,
              DataSourceId: null
            }],
            OutParams: [{ ParamName: 'Out0', ValueType: 'int' }],
            ScriptCode: AppParams.COMMON.USER_SCRIPT_TEMPLATE
          }
        },
        Desc: null
      },
      CompileMessage: null,
      LogicUserScriptDialogVisible: false,
      isFullscreen: false
    }
  },
  methods: {
    ShowNodeData () {
      // this.SourceNode = this.currentClickNodeMixin
      // const target = Utils.traverse(this.currentClickNodeMixin, [])
      // this.nodeInputParams = target
      this.SetFormValue(this.currentClickNodeMixin)
    },
    /**
     * 表单回显功能
     * @param _Node
     * @constructor
     */
    SetFormValue (_Node) {
      const LogicUserScript = {
        NodeLogic: {
          Script: {
            InputParams: [{ ParamName: null }],
            OutParams: [{ ParamName: null }],
            ScriptCode: AppParams.COMMON.USER_SCRIPT_TEMPLATE
          }
        },
        Desc: null
      }
      if (!Utils.IsEmpty(_Node.nodeInputParam?.NodeLogic)) {
        if (Utils.IsEmpty(_Node.nodeInputParam.NodeLogic.Script)) {
          _Node.nodeInputParam.NodeLogic.Script = {
            InputParams: [{ ParamName: null }],
            OutParams: [{ ParamName: null }],
            ScriptCode: AppParams.COMMON.USER_SCRIPT_TEMPLATE
          }
        }
        setTimeout(() => {
          this.LogicUserScript = _Node.nodeInputParam;
        }, 10)
      } else {
        this.LogicUserScript = LogicUserScript
      }
    },
    onChange (item, itemIndex) {
      if (!Utils.IsEmpty(item)) {
        this.LogicUserScript.NodeLogic.Script.InputParams[itemIndex].ParamName = item.ParamName
        this.LogicUserScript.NodeLogic.Script.InputParams[itemIndex].DataSource = item.DataSource
        this.LogicUserScript.NodeLogic.Script.InputParams[itemIndex].DataSourceId = item.nodeId
      }
    },
    /**
     * 删除脚本的输出参数
     * @param index
     */
    deleteScriptOutParam (index) {
      this.LogicUserScript.NodeLogic.Script.OutParams.splice(index, 1)
    },
    deleteScriptInputParam (index) {
      this.LogicUserScript.NodeLogic.Script.InputParams.splice(index, 1)
    },
    addScriptInputParam () {
      const Count = this.LogicUserScript.NodeLogic.Script.InputParams.length
      if (Utils.IsEmpty(this.LogicUserScript.NodeLogic.Script.InputParams)) {
        this.LogicUserScript.NodeLogic.Script.InputParams = [{
          TargetParamName: 'Input' + Count,
          ParamName: null,
          ValueType: 'int'
        }]
      } else {
        this.LogicUserScript.NodeLogic.Script.InputParams.push({
          TargetParamName: 'Input' + Count,
          ParamName: null,
          ValueType: 'int'
        })
      }
    },
    /**
     * 添加输出变量
     */
    addScriptOutParam () {
      const OutParams = this.LogicUserScript.NodeLogic.Script?.OutParams || [];
      const Count = OutParams.length;
      OutParams.push({ ParamName: 'Out' + Count, ValueType: 'int' });
      this.LogicUserScript.NodeLogic.Script.OutParams = OutParams;
    },
    /**
     * 窗口最大化
     */
    fullDialog () {
      this.isFullscreen = !this.isFullscreen
    },
    /**
     * 关闭窗口
     */
    handleCloseLogicUserScriptDialog () {
      this.$emit('close')
      this.LogicUserScriptDialogVisible = false
    },
    /**
     * 预编译
     */
    _PrecompiledScript (NodeName, NodeCommonInfo) {
      this._SaveNode(NodeName, NodeCommonInfo, true)
    },
    /**
     * 保存节点数据
     * @param NodeName
     * @param NodeCommonInfo
     * @param isPreCompiling
     */
    _SaveNode (NodeName, NodeCommonInfo, isPreCompiling = false) {
      const UserScript = JSON.parse(JSON.stringify(this.LogicUserScript))
      let vai = true
      UserScript.NodeLogic.Script.InputParams.forEach(i => {
        if (vai && Utils.IsEmpty(i.TargetParamName)) {
          MessageWarning('请输入变量名称')
          vai = false
        }
        if (vai && Utils.IsEmpty(i.ValueType)) {
          MessageWarning('请选择输入变量类型')
          vai = false
        }
        if (vai && (Utils.IsEmpty(i.DataSourceId) || i.DataSourceId <= 0)) {
          MessageWarning('请选择输入变量来源')
          vai = false
        }
      })
      UserScript.NodeLogic.Script.OutParams.forEach(i => {
        if (vai && Utils.IsEmpty(i.ParamName)) {
          MessageWarning('请输出输出变量名称')
          vai = false
        }
        if (vai && Utils.IsEmpty(i.ValueType)) {
          MessageWarning('请选择输出变量类型')
          vai = false
        }
      })
      if (vai) {
        new FlowNodeDataApi().Install(this.currentClickNodeMixin.id, Object.assign({}, UserScript), NodeName, isPreCompiling)
        if (!isPreCompiling) {
          this.handleCloseLogicUserScriptDialog()
        }
      }
    },
    ScriptCompileError (Error) {
      let msg = '编译成功，无异常'
      let type = 'success'
      if (!Utils.IsEmpty(Error.m_StringValue)) {
        msg = Error.m_StringValue
        type = 'error'
      }
      if (!Utils.IsEmpty(this.notifyC)) {
        this.notifyC.close()
      }
      this.notifyC = this.$notify({
        customClass: 'node_script_compile',
        dangerouslyUseHTMLString: true,
        message: msg,
        type: type,
        title: '编译结果',
        duration: 30000
      })
    }
  },
  mounted () {
    this.ShowNodeData()
    Emitter.on(AppParams.JAVA_SCRIPT_EVENT.NODE_SCRIPT_COMPILE_ERROR, this.ScriptCompileError)
  },
  beforeUnmount () {
    Emitter.off(AppParams.JAVA_SCRIPT_EVENT.NODE_SCRIPT_COMPILE_ERROR, this.ScriptCompileError)
  }
}
</script>

<style lang="less">


.node_script_compile {
  p {
    white-space: pre-line;
  }
}

.logic-user-script-dialog {
  width: 100%;
  min-width: 600px;
  height: calc(100vh - 110px);
  overflow-x: auto;

  flex: 1;
  display: flex;
  flex-direction: column;

  .user-script-params {
    .user-script-param {
      padding-right: 10px;

      .user-script-param-list {
        overflow-y: auto;
      }

      .user-script-param-item {
        display: flex;
        padding-top: 10px;
      }
    }
  }

  .user-script-space {
    flex: 1;
    padding: 10px 0;

    .user-script-edit {
      .go-editor-area {
        .monaco-editor {
          background-color: rgb(0 0 0 / 84%) !important;
        }
      }

    }
  }

  .user-script-desc {
    width: 300px;
    padding-left: 10px;
  }

  .el-dialog__body {
    padding-top: 20px;
    height: calc(100% - 100px);
  }

  .el-dialog__header {
    background-color: #545c64;
    padding: 20px 10px;

    .el-dialog__title {
      color: #ffffff;
    }
  }
}
</style>
